﻿using System.Collections.ObjectModel;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;

using Aliphant.ChatAI.ChatProxys;
using Aliphant.ChatAI.Interfaces;
using Aliphant.ChatAI.Models;
using Aliphant.ChatAI.Proxys;
using Aliphant.ChatAI.Tools;
using Aliphant.Common;
using Aliphant.Common.Helper;
using Aliphant.Mvvm.XEvent.Events;
using Aliphant.Mvvm.XEvent.Events.Base.SubScription;
using Aliphant.Mvvm.XEvent.UI;
using Aliphant.UI.AIChat.Models;
using Aliphant.UI.AIChat.Models.Stock;
using Aliphant.UI.Forms.Notify;
using Aliphant.UI.Windows;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Aliphant.UI.AIChat.ViewModels
{
    public class ChatRobotViewModel : BindableBase
    {
        private IChatAI? chatAI;
        private WindowEvent _windowEvent;

        private SubScriptionToken _subscriptionToken1;
        private SubScriptionToken _subscriptionToken2;

        //private Widget? stockWidget;

        public ChatRobotViewModel()
        {
            _windowEvent = AIChatModule.EventAgent.GetEvent<WindowEvent>();

            _subscriptionToken1 = _windowEvent.Subscribe(UpdateRobotConfigAction, (p) => p.Type == EventType.Action && p.WindowActionType == WindowActionType.Edit && p.EventId == EventIds.UpdateRobotConfig);
            _subscriptionToken2 = _windowEvent.Subscribe(ReleaseAction, (p) => p.Type == EventType.Action && p.WindowActionType == WindowActionType.Close && p.EventId == EventIds.Release);

            ReadAIConfig();
        }

        #region New

        #region Property

        private IDictionary<int, string> _intelligents = new Dictionary<int, string>();

        /// <summary>
        /// 选项卡索引
        /// </summary>
        private int _tabIndex;
        public int TabIndex
        {
            get => _tabIndex;
            set
            {
                SetProperty(ref _tabIndex, value);

                if (value == 0) return;

                if (_intelligents.ContainsKey(value))
                {
                    AIAgent = _intelligents[value];
                }
            }
        }

        private bool _tabEnabled = true;
        public bool TabEnabled { get => _tabEnabled; set => SetProperty(ref _tabEnabled, value); }

        /// <summary>
        /// AI模型文件路径
        /// </summary>
        private string _aiAgent = string.Empty;
        public string AIAgent
        {
            get => _aiAgent;
            set
            {
                SetProperty(ref _aiAgent, value);
                StartGPTAgent(value);
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        private string _sendMessage = string.Empty;
        public string SendMessage
        {
            get => _sendMessage; set
            {
                SetProperty(ref _sendMessage, value);

                SendBtnEnabled = !string.IsNullOrEmpty(_sendMessage);
            }
        }

        /// <summary>
        /// 输入框编辑状态
        /// </summary>
        private bool _inputEnabled = true;
        public bool InputEnabled { get => _inputEnabled; set => SetProperty(ref _inputEnabled, value); }


        /// <summary>
        /// 模型厂家
        /// </summary>
        private string _aifactory = string.Empty;
        public string AIFactory
        {
            get => _aifactory;
            set
            {
                SetProperty(ref _aifactory, value);

                var chatModel = _factoryDic[_aifactory];
                if (chatModel != null)
                {
                    AIConfig?.ResetConfig();
                    AIConfig = chatModel;
                }
            }
        }

        /// <summary>
        /// 当前AI
        /// </summary>
        private ChatAIConfig? _aiConfig;
        public ChatAIConfig? AIConfig { get => _aiConfig; set => SetProperty(ref _aiConfig, value); }

        /// <summary>
        /// AI列表
        /// </summary>
        public ObservableCollection<string> AIFactoryCollection { get; private set; } = new ObservableCollection<string>();

        /// <summary>
        /// 对话列表
        /// </summary>
        public ObservableCollection<ChatBubble> ChatList { get; set; } = new ObservableCollection<ChatBubble>();

        private Dictionary<string, ChatAIConfig> _factoryDic = [];

        #endregion

        #region Command

        public ICommand SendCommand
        {
            get => new UICommand<string>(str =>
            {
                if (string.IsNullOrEmpty(SendMessage) && string.IsNullOrEmpty(str)) return;

                string msg = SendMessage;
                if (!string.IsNullOrEmpty(str))
                {
                    msg = str;
                }

                ChatList.Add(new UserBubble(msg));

                chatAI?.AddMessage(msg);
                chatAI?.WeekUp();

                SendMessage = "回答输出中，请稍后操作或停止回答。";

                SendBtnVisible = Visibility.Collapsed;
                StopBtnVisible = Visibility.Visible;
                InputEnabled = false;
                TabEnabled = false;

                ScrollToEnd();
            });
        }

        public ICommand StopCommand
        {
            get => new UICommand<object>(obj =>
            {
                chatAI?.Pause();

                SendMessage = string.Empty;
                SendBtnVisible = Visibility.Visible;
                StopBtnVisible = Visibility.Collapsed;
                InputEnabled = true;
                TabEnabled = true;
            });
        }

        public ICommand NewChatCommand
        {
            get => new UICommand<object>(obj =>
            {
                SendMessage = string.Empty;
                ChatList.Clear();
                chatAI?.NewSession();
            });
        }

        public ICommand UpdateCommand
        {
            get => new UICommand<object>(obj =>
            {
                if (AIConfig == null || _stockGPT == null) return;

                GptConfig gpt = new GptConfig(_aiAgent);
                AIConfig.Clone(ref gpt);
                _stockGPT.Clone(ref gpt);

                // 重新加载AI
                chatAI?.Load(gpt);

            });
        }


        #endregion

        /// <summary>
        /// 启动AI智能体
        /// </summary>
        /// <param name="path">智能体路径</param>
        private void StartGPTAgent(string path)
        {
            ChatList.Clear();

            // 加载智能体
            _stockGPT = LoadAgent(path);
            if (AIConfig == null || _stockGPT == null) return;

            StockRoleSystem = _stockGPT.system;

            GptConfig gpt = new GptConfig(path);
            AIConfig.Clone(ref gpt);
            _stockGPT.Clone(ref gpt);

            // 启动智能体
            chatAI?.Load(gpt);
            chatAI?.RefreshSession();

            Logger.Info("启动ChatAI");
        }


        /// <summary>
        /// 读取AI配置
        /// </summary>
        public void ReadAIConfig()
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "configs", "ai.json");
            JsonHelper.ReadJson<ChatAISetting>(path, out var ai);

            chatAI = new GptAgent();
            chatAI.InPutHandle += ChatAI_InPutHandler;
            chatAI.OutPutHandle += ChatAI_OutPutHandler;
            chatAI.Start();

            if (ai == null) return;

            foreach (var ig in ai.param.intelligents)
            {
                _intelligents.Add(ig.index, ig.path);
            }

            foreach (var item in ai.apiFactory)
            {
                ChatAIConfig config = new ChatAIConfig(item);
                config.SaveEvent += SaveAIConfig;
                _factoryDic.Add(config.Name, config);
                AIFactoryCollection.Add(config.Name);
            }

            if (!string.IsNullOrEmpty(ai.param.factory))
            {
                AIFactory = ai.param.factory;
                AIConfig?.LoadConfig(ai.param);
            }

            //if (_intelligents.ContainsKey(1))
            //{
            //    StockAIAgent = _intelligents[1];
            //}

        }

        /// <summary>
        /// 保存AI配置
        /// </summary>
        public void SaveAIConfig()
        {
            ChatAISetting settins = new ChatAISetting();
            settins.param.factory = AIFactory;
            settins.param.model = AIConfig?.Model ?? string.Empty;
            settins.param.stream = AIConfig?.Stream ?? true;

            List<Intelligent> igs = new();
            foreach (var ig in _intelligents)
            {
                igs.Add(new Intelligent
                {
                    index = ig.Key,
                    path = ig.Value,
                });
            }
            settins.param.intelligents = igs.ToArray();

            List<ApiFactory> factories = new List<ApiFactory>();
            foreach (var item in _factoryDic.Values)
            {
                factories.Add(new ApiFactory
                {
                    name = item.Name,
                    api = item.API,
                    key = item.ApiKey,
                    models = item.ModelCollection.ToArray()
                });
            }
            settins.apiFactory = factories.ToArray();

            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "configs", "ai.json");
            JsonHelper.SaveToJson(ref settins, path);
        }

        /// <summary>
        /// 加载智能体
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private IntelligentAgent? LoadAgent(string path)
        {
            string file = Path.Combine(path, "agent.json");
            JsonHelper.ReadJson<IntelligentAgent>(file, out var agent);
            return agent;
        }

        /// <summary>
        /// 保存智能体
        /// </summary>
        /// <param name="agent"></param>
        /// <param name="path"></param>
        private void SaveAgent(IntelligentAgent agent, string path)
        {
            string file = Path.Combine(path, "agent.json");
            JsonHelper.SaveToJson(ref agent, file);
        }


        /// <summary>
        /// 输入事件
        /// </summary>
        private void ChatAI_InPutHandler()
        {
            // 恢复输入框状态

            SendBtnVisible = Visibility.Visible;
            StopBtnVisible = Visibility.Collapsed;
            InputEnabled = true;
            TabEnabled = true;
            SendMessage = string.Empty;
        }

        /// <summary>
        /// 输出事件
        /// </summary>
        /// <param name="content"></param>
        private void ChatAI_OutPutHandler(ChatAI.Models.ChatContent content)
        {
            if (content.Role == "assistant" && !string.IsNullOrEmpty(content.Message))
            {
                if (_latestAnswerBubble == null)
                {
                    _latestAnswerBubble = new AnswerBubble();
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        ChatList.Add(_latestAnswerBubble);
                    });
                }
                _latestAnswerBubble.Message += content.Message;
            }
            else if (content.Role == "reasoning" && !string.IsNullOrEmpty(content.Message))
            {
                if (_latestReasoningBubble == null)
                {
                    _latestReasoningBubble = new ThinkingBubble();
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        ChatList.Add(_latestReasoningBubble);
                    });
                }
                _latestReasoningBubble.Message += content.Message;
            }
            else if (content.Role == "user")
            {
                //用户提问
                ChatList.Add(new UserBubble(content.Message));
            }
            else if (content.Role == "END")
            {
                _latestAnswerBubble = null;
                _latestReasoningBubble = null;
            }

            ScrollToEnd();
        }

        #endregion

        #region 通用智能体

        #endregion

        #region 股神智能体

        private IntelligentAgent? _stockGPT;

        /// <summary>
        /// 股神设定
        /// </summary>
        private string _stockRoleSystem = string.Empty;
        public string StockRoleSystem
        {
            get => _stockRoleSystem;
            set
            {
                SetProperty(ref _stockRoleSystem, value);

                if (_stockGPT == null) return;
                _stockGPT.system = value;
                SaveAgent(_stockGPT, AIAgent);

                if (AIConfig == null) return;

                GptConfig gpt = new GptConfig(_aiAgent);
                AIConfig.Clone(ref gpt);
                _stockGPT.Clone(ref gpt);

                // 重新加载AI
                chatAI?.Load(gpt);
            }
        }

        /// <summary>
        /// 天数
        /// </summary>
        private int _ndays = 60;
        public int NDays { get => _ndays; set { SetProperty(ref _ndays, value); } }

        /// <summary>
        /// 分时
        /// </summary>
        private int _ntimes = 1;
        public int NTimes { get => _ntimes; set => SetProperty(ref _ntimes, value); }

        /// <summary>
        /// 股票名称
        /// </summary>
        private string _sharesName = string.Empty;
        public string SharesName { get => _sharesName; set { SetProperty(ref _sharesName, value); } }

        /// <summary>
        /// 股票代码
        /// </summary>
        private string _sharesCode = string.Empty;
        public string SharesCode { get => _sharesCode; set { SetProperty(ref _sharesCode, value); } }

        /// <summary>
        /// 买点
        /// </summary>
        private string _buyPoint = string.Empty;
        public string BuyPoint { get => _buyPoint; set { SetProperty(ref _buyPoint, value); } }

        /// <summary>
        /// 其他信息
        /// </summary>
        private string _otherMsg = string.Empty;
        public string OtherMsg { get => _otherMsg; set { SetProperty(ref _otherMsg, value); } }

        /// <summary>
        /// 分析目标
        /// </summary>
        private string _target = string.Empty;
        public string Target { get => _target; set { SetProperty(ref _target, value); } }

        /// <summary>
        /// K线数据
        /// </summary>
        private string _klines = string.Empty;
        public string KLines { get => _klines; set { SetProperty(ref _klines, value); } }

        /// <summary>
        /// 主力资金数据
        /// </summary>
        private string _capitals = string.Empty;
        public string Capitals { get => _capitals; set { SetProperty(ref _capitals, value); } }

        /// <summary>
        /// 分时数据
        /// </summary>
        private string _timeSharing = string.Empty;
        public string TimeSharing { get => _timeSharing; set => SetProperty(ref _timeSharing, value); }


        public ICommand TestApiCommand
        {
            get => new UICommand<object>(obj =>
            {
                //NotifyIconHelper.ShowBalloon("系统通知测试", "XChatAI", 0, test);
                //test++;
                //test %= 4;
            });
        }

        /// <summary>
        /// K线
        /// </summary>
        public ICommand KLinesCommand
        {
            get => new UICommand<object>(async obj =>
            {
                await GetKlineDatas(NDays);
            });
        }

        /// <summary>
        /// 主力资金
        /// </summary>
        public ICommand MainCapitalCommand
        {
            get => new UICommand<object>(async obj =>
            {
                await GetMainCapitalDatas();
            });
        }

        /// <summary>
        /// 股票分析
        /// </summary>
        public ICommand AnalysisSharesCommand
        {
            get => new UICommand<object>(async obj =>
            {
                await GetKlineDatas(NDays);
                await GetMainCapitalDatas();
                await GetTimeSharingDatas(NTimes);
                var fiveLevel = await GetLevelFive();

                string target = Target;

                string sendMsg = @$"{SharesName}，代码：{SharesCode}
【当前时间】
{DateTime.Now.ToString("yyyy-MM-dd HH:mm dddd")}
【K线】
[
{KLines}
]
【主力资金】
[
{Capitals}
]
【{NTimes}分分时】
[
{TimeSharing}
]
【五档】
[
{fiveLevel}
]
【持仓】
{BuyPoint}
【其他】
{OtherMsg}
【目标】
{target}";
                SendMessage = sendMsg.Trim();
                InputScrollToEnd(SendMessage);
            });
        }

        /// <summary>
        /// 追加分析
        /// </summary>
        public ICommand AdditionalForecastCommand
        {
            get => new UICommand<object>(async obj =>
            {
                await GetKlineDatas(NDays);
                await GetMainCapitalDatas();
                await GetTimeSharingDatas(NTimes);
                var fiveLevel = await GetLevelFive();

                string target = string.IsNullOrEmpty(Target)
                ? "根据最新的K线、主力资金、分时数据以及五档盘口数据，提供最新操作策略，并标注出可以操作的信号"
                : Target;

                string sendMsg = @$"{SharesName}，代码：{SharesCode}
【当前时间】
{DateTime.Now.ToString("yyyy-MM-dd HH:mm dddd")}
【K线】
[
{KLines}
]
【主力资金】
[
{Capitals}
]
【{NTimes}分分时】
[
{TimeSharing}
]
【五档】
[
{fiveLevel}
]
【持仓】
{BuyPoint}
【其他】
{OtherMsg}
【目标】
{target}";
                SendMessage = sendMsg.Trim();
                InputScrollToEnd(SendMessage);
            });
        }

        /// <summary>
        /// 主力资金流向排行
        /// </summary>
        public ICommand CapitalFlowCommand
        {
            get => new UICommand<object>(async obj =>
            {
                if (NDays == 0)
                {
                    string list = await GetCpitalFlow(NDays);
                    string msg = $@"【资金流向{NDays}】
{list}
【目标】
{Target}";
                    SendMessage = msg.Trim();
                    InputScrollToEnd(SendMessage);
                }
            });
        }


        #region 股票API

        /// <summary>
        /// 获取K线数据
        /// </summary>
        /// <param name="days"></param>
        /// <returns></returns>
        private async Task GetKlineDatas(int days)
        {
            KLines = string.Empty;
            _klineArr = await SharesAPI.GetKLinesAsync(SharesCode, days);
            if (_klineArr.Length <= 0) return;

            var tempList = _klineArr.ToList();
            SharesName = tempList[0];
            tempList.RemoveAt(0);
            _klineArr = tempList.ToArray();

            KLines = ArrayToString(_klineArr);
        }

        /// <summary>
        /// 获取股票主力资金流向数据
        /// </summary>
        /// <returns></returns>
        private async Task GetMainCapitalDatas()
        {
            Capitals = string.Empty;
            if (_klineArr == null) return;

            _capitalArr = await SharesAPI.GetMainCapitalAsync(SharesCode, _klineArr.Length);
            if (_capitalArr.Length <= 0) return;

            var tempList = _capitalArr.ToList();
            SharesName = tempList[0];
            tempList.RemoveAt(0);
            _capitalArr = tempList.ToArray();

            Capitals = ArrayToString(_capitalArr);
        }

        /// <summary>
        /// 获取股票分时数据
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        private async Task GetTimeSharingDatas(int time)
        {
            TimeSharing = string.Empty;

            _timeSArr = await SharesAPI.GetTimeSharingAsync(SharesCode, time);
            if (_timeSArr.Length <= 0) return;

            var tempList = _timeSArr.ToList();
            SharesName = tempList[0];
            tempList.RemoveAt(0);
            _timeSArr = tempList.ToArray();

            TimeSharing = ArrayToString(_timeSArr);
        }

        /// <summary>
        /// 获取资金流向排行
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        private async Task<string> GetCpitalFlow(int time)
        {
            var arr = await SharesAPI.GetCpitalFlowAsync(time);
            return ArrayToString(arr);
        }

        private async Task<string> GetLevelFive()
        {
            string code = await SharesAPI.SearchStockCode(SharesCode);
            if (string.IsNullOrEmpty(code))
            {
                return string.Empty;
            }

            string[] paramArr = await SharesAPI.QueryCurrentDataAsync(code);

            StockDetail stock = new StockDetail(paramArr);

            Logger.Info(JsonConvert.SerializeObject(stock));

            StringBuilder askSB = new StringBuilder();
            StringBuilder bidSB = new StringBuilder();

            for (int i = 0; i < 5; i++)
            {
                askSB.AppendLine($"\"{stock.LevelFiveAsk[i].Name},{stock.LevelFiveAsk[i].Price},{stock.LevelFiveAsk[i].OrderSize}\",");
                bidSB.AppendLine($"\"{stock.LevelFiveBid[i].Name},{stock.LevelFiveBid[i].Price},{stock.LevelFiveBid[i].OrderSize}\",");
            }

            string res = askSB.ToString() + bidSB.ToString();
            return res.Trim('\r', '\n', ',');
        }

        private string ArrayToString(string[] arr)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in arr)
            {
                sb.AppendLine($"\"{item}\",");
            }

            return sb.ToString().Trim(',', '\r', '\n');
        }


        #endregion

        #endregion


        /// <summary>
        /// API
        /// </summary>
        private string _api = string.Empty;
        public string API
        {
            get => _api; set
            {
                if (_api == value) return;
                SetProperty(ref _api, value);
                SaveRoleSetting();
            }
        }

        /// <summary>
        /// API-KEY
        /// </summary>
        private string _apiKey = string.Empty;
        public string ApiKey
        {
            get => _apiKey; set
            {
                if (_apiKey == value) return;
                SetProperty(ref _apiKey, value);
                SaveRoleSetting();
            }
        }

        /// <summary>
        /// GPT模型
        /// </summary>
        private string _chatModel = string.Empty;
        public string ChatModel
        {
            get => _chatModel; set
            {
                if (_chatModel == value) return;
                SetProperty(ref _chatModel, value);
                SaveRequestTemplate();
            }
        }


        private string _robotConfig = string.Empty;
        public string RobotConfig
        {
            get => _robotConfig;
            set
            {
                SetProperty(ref _robotConfig, value);
                //InitChatAI(value);
            }
        }


        /// <summary>
        /// AI设定
        /// </summary>
        private string _roleSystem = string.Empty;
        public string RoleSystem
        {
            get => _roleSystem; set
            {
                if (_robotConfig == value) return;
                SetProperty(ref _roleSystem, value);
                SaveRoleSetting();
            }
        }

        /// <summary>
        /// 机器人名字
        /// </summary>
        private string _robotName = string.Empty;
        public string RobotName
        {
            get => _robotName; set
            {
                if (_robotName == value) return;
                SetProperty(ref _robotName, value);
                SaveRoleSetting();
            }
        }

        /// <summary>
        /// 打招呼
        /// </summary>
        private string _greetings = string.Empty;
        public string Greetings
        {
            get => _greetings; set
            {
                if (_greetings == value) return;
                SetProperty(ref _greetings, value);
                SaveRoleSetting();
            }
        }


        private SixLines _sixLines = new SixLines();
        public SixLines SixLines { get => _sixLines; set => SetProperty(ref _sixLines, value); }

        private string _tellingQuestion = string.Empty;
        public string TellingQuestion { get => _tellingQuestion; set => SetProperty(ref _tellingQuestion, value); }

        private Visibility _sendBtnVisible = Visibility.Visible;
        public Visibility SendBtnVisible { get => _sendBtnVisible; set => SetProperty(ref _sendBtnVisible, value); }

        private Visibility _stopBtnVisible = Visibility.Collapsed;
        public Visibility StopBtnVisible { get => _stopBtnVisible; set => SetProperty(ref _stopBtnVisible, value); }

        private bool _sendBtnEnabled;
        public bool SendBtnEnabled { get => _sendBtnEnabled; set => SetProperty(ref _sendBtnEnabled, value); }

        private ChatBubble? _latestAnswerBubble;
        private ChatBubble? _latestReasoningBubble;

        private string[]? _klineArr;
        private string[]? _capitalArr;
        private string[]? _timeSArr;


        public ICommand SixLineDivinationCommand
        {
            get => new UICommand<object>(obj =>
            {
                string msg = $@"【起卦】铜钱卦
【六爻】
上爻：{SixLines.GetYingYang(SixLines.SixLine)}
五爻：{SixLines.GetYingYang(SixLines.FiveLine)}
四爻：{SixLines.GetYingYang(SixLines.FourLine)}
三爻：{SixLines.GetYingYang(SixLines.ThreeLine)}
二爻：{SixLines.GetYingYang(SixLines.TwoLine)}
初爻：{SixLines.GetYingYang(SixLines.OneLine)}
【问题】{TellingQuestion}
【时间】{DateTime.Now.ToString("yyyy-MM-dd H:m:s dddd")}";
                SendMessage = msg.Trim();
                InputScrollToEnd(SendMessage);
            });
        }

        public ICommand BirthdayDivinationCommand
        {
            get => new UICommand<object>(obj =>
            {
                string msg = $@"【八字】{SixLines.BirthdayWorld}
【生日】
【问题】{TellingQuestion}
【时间】{DateTime.Now.ToString("D")}";
                SendMessage = msg.Trim();
                InputScrollToEnd(SendMessage);
            });
        }

        public ICommand SixLineRecoverCommand
        {
            get => new UICommand<object>(obj =>
            {
                SixLines.OneLine = 0;
                SixLines.TwoLine = 0;
                SixLines.ThreeLine = 0;
                SixLines.FourLine = 0;
                SixLines.FiveLine = 0;
                SixLines.SixLine = 0;
            });
        }


        /// <summary>
        /// 对话列表滚动到底部
        /// </summary>
        private void ScrollToEnd()
        {
            _windowEvent.Publish(new WindowEvent
            {
                Type = EventType.Action,
                WindowActionType = WindowActionType.Update,
                EventId = EventIds.ScrollToEnd,
            });
        }

        /// <summary>
        /// 输入框光标移动到末尾
        /// </summary>
        /// <param name="msg"></param>
        private void InputScrollToEnd(string msg = "")
        {
            _windowEvent.Publish(new WindowEvent
            {
                Data = msg,
                Type = EventType.Action,
                WindowActionType = WindowActionType.Update,
                EventId = EventIds.InputScrollToEnd,
            });
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        /// <param name="event"></param>
        private void ReleaseAction(WindowEvent @event)
        {
            Release();
        }

        /// <summary>
        /// 更新智能体模型
        /// </summary>
        /// <param name="event"></param>
        private void UpdateRobotConfigAction(WindowEvent @event)
        {
            if (@event.Data is string file)
            {
                RobotConfig = file;
            }
        }

        public void Release()
        {
            chatAI?.Stop();
            //stockWidget?.Close();
        }


        #region 废弃，下个版本删除


        private void SaveRoleSetting()
        {
            string fileName = System.IO.Path.Combine(RobotConfig, "setting.json");
            JsonHelper.ReadJson(fileName, out ChatAI.Models.ChatSetting? settings);

            if (settings == null)
            {
                return;
            }

            settings.System = _roleSystem;
            settings.Key = _apiKey;
            settings.API = _api;
            settings.Name = _robotName;
            settings.Tips = _greetings;

            JsonHelper.SaveToJson(ref settings, fileName);
        }

        private void SaveRequestTemplate()
        {
            string fileName = System.IO.Path.Combine(RobotConfig, "request.json");
            string content = JsonHelper.ReadSeriesNoFormat(fileName);

            JObject json = JObject.Parse(content);
            json["model"] = _chatModel;

            JsonHelper.SaveNoFormat(fileName, json.ToString());
        }


        #endregion
    }
}
